package org.sagitta.httprpc.json.adaptor;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagitta.httprpc.ResponseMashaller;
import org.sagitta.httprpc.exception.RPCException;
import org.sagitta.httprpc.message.ExceptionResponse;
import org.sagitta.httprpc.message.FaultResponse;
import org.sagitta.httprpc.message.Response;

public class JSONResponseMashaller implements ResponseMashaller {
	
	private static final Log log = LogFactory.getLog(JSONResponseMashaller.class);
	@Override
	public byte[] marshal(Response response) throws RPCException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void marshal(Response response, OutputStream stream)
			throws RPCException {
		JSONObject jsonObj = new JSONObject();
		jsonObj.put(getResponseTitle(response), response);
		String result = jsonObj.toString();
		try {
			if (log.isDebugEnabled()) {
				log.debug("Response: " + result);
			}
			BufferedOutputStream bos = new BufferedOutputStream(stream); 
			bos.write(result.getBytes());
			bos.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RPCException(RPCException.RESPONSEMASHLLERROR);
		}
	}
	
	private String getResponseTitle(Response response) {
		if (response instanceof ExceptionResponse) {
			return "exception";
		} else if (response instanceof FaultResponse ) {
			return "fault";
		} 
		return "response";
	}
	

}
